package org.smr.ministore.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.blade.dao.base.BaseMapper;
import org.blade.utils.IdGenUtils;
import org.blade.utils.Pager;
import org.blade.service.base.AbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smr.ministore.dao.DictionaryOrganMapper;
import org.smr.ministore.entities.DictionaryOrgan;
import org.smr.ministore.service.DictionaryOrganService;

import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.stereotype.Service;

@Service("DictionaryOrganService")
public class DictionaryOrganServiceImpl extends AbstractService<Long, DictionaryOrgan> implements DictionaryOrganService {


    private static Logger logger = LoggerFactory.getLogger(DictionaryOrganServiceImpl.class);

	private static final int ZERO = 0;

	@Autowired
	private DictionaryOrganMapper mapper;

	public DictionaryOrganServiceImpl(DictionaryOrganMapper mapper) {
		super(mapper);
	}

	public int save(DictionaryOrgan entity) {
		super.saveAttatch(entity);

		return mapper.insert(entity);
	}

	public int updateById(DictionaryOrgan id) {
		super.modifyAttach(id);

		return mapper.updateById(id);
	}

	public DictionaryOrgan queryById(Long id) {
		return mapper.selectById(id);
	}

	public int deleteById(Long id) {
		return mapper.deleteById(id);
	}

	public Pager<DictionaryOrgan> paginate( DictionaryOrgan entity, Long pageSize, Long pageNum) {

		Pager<DictionaryOrgan> pager = new Pager( pageSize, pageNum );
		List list  = mapper.pagination(entity, pager);
		pager.setEntities(list);
		return pager;
    }
	
	public int batchSave(List<DictionaryOrgan> entities) {
        this.batchSaveAttatch(entities);
		return mapper.batchInsert(entities);
	}


    public int batchModify(List<DictionaryOrgan> entities) {
        this.batchModifyAttatch(entities);
        return mapper.batchUpdate(entities);
        }


    public int deleteByIdLogical(Long id) {
        return mapper.deleteByIdLogical(id);
    }


	public int assignedDictionary(List<DictionaryOrgan> dictionaryOrganList, Long organId) {
		int effectCount = 0;
		effectCount = this.mapper.deleteByOrgan(organId);

		List<DictionaryOrgan> dictionaryOrgansForAdd = new ArrayList<DictionaryOrgan>();
		List<DictionaryOrgan> dictionaryOrgansForUpdate = new ArrayList<DictionaryOrgan>();

		for( DictionaryOrgan dictionaryOrgan : dictionaryOrganList ){

			if(ObjectUtils.notEqual(dictionaryOrgan.getId(), null)){
				dictionaryOrgansForUpdate.add(dictionaryOrgan);
			}else{
				dictionaryOrgansForAdd.add(dictionaryOrgan);

			}
		}

		if( dictionaryOrgansForAdd.size() > ZERO ){

			effectCount += this.batchSave(dictionaryOrgansForAdd);
		}

		if(dictionaryOrgansForUpdate.size() > ZERO){
			effectCount += this.batchModify(dictionaryOrgansForUpdate);

		}

		return effectCount;

	}

	public Long getId() {
		return IdGenUtils.getNextLongId();
	}
}
